import puppeteer from 'puppeteer-core';
import { launch } from 'chrome-launcher';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import fs from 'fs';
import { writeFile } from 'fs/promises';
import path from 'path';

async function convertArticleToHtml(url, outputPath) {
    // 使用chrome-launcher启动Chrome
    const chrome = await launch({
        chromeFlags: ['--headless']
    });

    const browser = await puppeteer.connect({
        browserURL: `http://localhost:${chrome.port}`,
        defaultViewport: null
    });
    try {
        const page = await browser.newPage();
        await page.goto(url, { waitUntil: 'networkidle0' });

        // 获取文章内容和图片URL
        const articleData = await page.evaluate(() => {
            // 尝试找到主要内容区域
            const article = document.querySelector('#img-content') ||
                document.querySelector('.article') ||
                document.querySelector('.content') ||
                document.querySelector('main') ||
                document.body;

            // 获取所有图片的URL和HTML
            const images = Array.from(article.getElementsByTagName('img'));
            const imageData = images.map(img => ({
                src: img.dataset.src || img.src,
                html: img.outerHTML
            }));

            return {
                title: document.title,
                content: article.innerHTML,
                images: imageData
            };
        });

        // 在Node.js环境中处理图片转换
        const newPage = await browser.newPage();
        //console.log(articleData.images)
        const json = {}
            ;
        for (const img of articleData.images) {
            if (!img.src || img.src.startsWith('data:')) continue;

            try {
                // 确保使用完整的URL路径
                const imgUrl = new URL(img.src, url).href;
                console.log(`Converting image: ${imgUrl}`);
                const response = await fetch(imgUrl);
                if (!response.ok) {
                    throw new Error(`Failed to load image: ${response.status} ${response.statusText}`);
                }

                // 获取图片的Content-Type
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.startsWith('image/')) {
                    throw new Error('Not a valid image response');
                }

                // 获取图片的二进制数据
                const imageBuffer = await response.arrayBuffer();
                const base64 = Buffer.from(imageBuffer).toString('base64');

                // 创建images目录如果不存在
                const imagesDir = path.join(process.cwd(), 'images');
                await fs.promises.mkdir(imagesDir, { recursive: true });

                // 生成图片文件名并保存
                const ext = contentType.split('/')[1] || 'jpg';
                const imageName = `image_${Date.now()}_${Math.floor(Math.random() * 1000)}.${ext}`;
                //const imagePath = path.join(imagesDir, imageName);
                //await fs.promises.writeFile(imagePath, Buffer.from(imageBuffer));

                //json[imageName] = base64;

                // 保留base64转换用于调试
                articleData.content = articleData.content.replace(
                    img.html,
                    `<img src="data:${contentType};base64,${base64}" alt="${imageName}">`
                );
            } catch (error) {
                console.warn(`Failed to convert image: ${img.src} - ${error.message}`);
            }
        }
        await newPage.close();
        //await writeFile(outputPath.replace('.html', '.json'), JSON.stringify(json), 'utf8');
        const article = articleData;

        // 清理HTML内容，移除script、emoji等非基础元素
        const cleanContent = article.content
            .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
            .replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '')
            .replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi, '')
            .replace(/<svg\b[^<]*(?:(?!<\/svg>)<[^<]*)*<\/svg>/gi, '')
            .replace(/<[^>]+\sclass="[^"]*emoji[^"]*"[^>]*>/gi, '')
            .replace(/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu, '')
            .replace(/\n\s*\n/g, '\n');

        // 生成简化的HTML
        const html = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    ${cleanContent}
</body>
</html>`;

        // 保存HTML到文件
        await writeFile(outputPath, html, 'utf8');
        return outputPath;

    } finally {
        await browser.close();
        await chrome.kill();
    }
}

// 命令行参数处理
const argv = yargs(hideBin(process.argv))
    .usage('Usage: $0 <url> [output]')
    .positional('url', {
        describe: 'URL to convert',
        type: 'string'
    })
    .positional('output', {
        describe: 'Output file path',
        type: 'string'
    })
    .demandCommand(1, 'Please provide a URL to convert')
    .argv;

// 主函数
async function main() {
    try {
        const url = argv._[0];
        const defaultFileName = `article_${Date.now()}.html`;
        const outputPath = argv._[1] || path.join(process.cwd(), defaultFileName);

        const savedPath = await convertArticleToHtml(url, outputPath);
        console.log(`文章已成功保存到: ${savedPath}`);
    } catch (error) {
        console.error('Error:', error.message);
        process.exit(1);
    }
}

main();